<template>
  <master title="简易案件">
    <!-- Author: guyang -->
    <!-- 顶部布局 -->
    <div class="searchForm">
      <div class="searchFormInputs">
        <el-input class="searchFormInput" v-model="params.id" placeholder="案件编号"></el-input>
      </div>
      <!-- <div class="searchFormInputs">
        <el-select v-model="params.urgency" filterable placeholder="紧急程度">
          <el-option v-for="item in urgencyValue" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div> -->
      <div class="searchFormInputs">
        <el-select v-model="params.source" filterable placeholder="案件来源">
          <el-option v-for="item in sourceValue" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <!-- <div class="searchFormInputs">
        <el-select v-model="params.type" filterable placeholder="类型">
          <el-option v-for="item in typeValue" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div> -->
      <div class="searchFormInputs">
        <el-input class="searchFormInput" v-model="location1" placeholder="案件位置"></el-input>
      </div>
      <div class="searchFormInputs">
        <el-date-picker v-model="value1" type="datetimerange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </div>
      <div class="searchFormInputs">
        <el-button type="primary" icon="el-icon-search" @click="searchList">查询</el-button>
      </div>
    </div>
    <!-- 列表数据 -->
    <div class="el-table">
      <el-table :data="rows" stripe style="width: 100%">

        <el-table-column prop="id" label="编号">
          <template slot-scope="scope">
            <div class="text3row">{{scope.row.id}}</div>
          </template>
         </el-table-column>
        <el-table-column prop="description" label="案件描述">
          <template slot-scope="scope">
            <div class="text3row">{{scope.row.description}}</div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="urgency" label="紧急程度">
          <template slot-scope="scope">
            <div v-if="scope.row.urgency==='1'">普通</div>
            <div v-if="scope.row.urgency==='2'">紧急</div>
          </template>
        </el-table-column> -->
        <el-table-column prop="source" label="案件来源">
          <template slot-scope="scope">
            <div v-if="scope.row.source==='1'">12319</div>
            <div v-if="scope.row.source==='2'">城管通</div>
            <div v-if="scope.row.source==='3'">其他</div>
          </template>
        </el-table-column>
        <!-- 1-新案件，2-延期，3-挂账，4-回退,5-已处理 -->
        <!-- <el-table-column prop="applyType" label="申请类型">
          <template slot-scope="scope">
            <div v-if="scope.row.applyType==='1'">新案件</div>
            <div v-if="scope.row.applyType==='2'">简易案件</div>
          </template>
        </el-table-column> -->
        <el-table-column prop="surplusTime" label="案件剩余处理时间（小时）"> </el-table-column>
        <!-- <el-table-column prop="type" label="类型">
          <template slot-scope="scope">
            <div v-if="scope.row.type==='1'">事件</div>
            <div v-if="scope.row.type==='2'">部件</div>
          </template>
        </el-table-column> -->
        <el-table-column prop="createTimeString" label="创建时间"></el-table-column>
        <el-table-column prop="location" label="案件位置">
          <template slot-scope="scope">
            <div class="text3row">{{scope.row.location}}</div>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            {{scope.row.status==1?'待处理':scope.row.status==2?'处理中':scope.row.status==3?'待审核':scope.row.status==4?'结案':scope.row.status==5?'立案驳回审核':scope.row.status==6?'处理人申请延期':scope.row.status==7?'立案申请延期':'同意延期'}}
          </template>
        </el-table-column>

        <!-- 操作按钮 -->
        <el-table-column prop="applyType" label="操作" width="320">
          <template slot-scope="scope">
            <div>
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="appoint(scope.row)">处理</el-button>
            </div>
            <!-- <div v-if="scope.row.applyType==='1'">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="appoint(scope.row)">派遣</el-button>
            </div>
            <div v-else>
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="aggree(scope.row)">同意</el-button>
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="reject(scope.row)">拒绝</el-button>
            </div> -->
            <!-- <div class="martop20">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="detailButton(scope.row)">
                详情</el-button>
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="caseLogButton(scope.row)">流程</el-button>
            </div> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="el-pagination">
      <el-pagination @size-change="sizeChange" @current-change="currentChange" :current-page="params.pageNum"
        :page-sizes="[10, 100, 200, 300, 400]" :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 编辑和新增组件 -->
    <el-dialog :title="editForm.id ? '编辑案例' : '新增案例'" :visible.sync="visible">
      <el-form ref="editForm" :model="editForm">
        <el-form-item label="申请类型">
          <el-select v-model="applyType" filterable placeholder="请选择">
            <el-option v-for="item in applyTypeValue" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="紧急程度">
          <el-select v-model="urgency" filterable placeholder="请选择">
            <el-option v-for="item in urgencyValue" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="案件来源">
          <el-select v-model="source" filterable placeholder="请选择">
            <el-option v-for="item in sourceValue" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请人">
          <el-select v-model="applicant" filterable placeholder="请选择">
            <el-option v-for="item in applicantValue" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="上报时间">
          <div class="block">
            <el-date-picker v-model="upPortTime" type="datetime" placeholder="选择日期时间">
            </el-date-picker>
          </div>
        </el-form-item> -->
        <el-form-item class="row" label="剩余完成时间">
          <el-input type="number" placeholder="请输入" v-model="surplusTime"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="type" filterable placeholder="请选择">
            <el-option v-for="item in typeValue" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="大类">
          <el-select v-model="firstType" filterable placeholder="请选择">
            <el-option v-for="item in firstTypeValue" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="row" label="小类">
          <el-input type="text" placeholder="请输入" v-model="secondType"></el-input>
        </el-form-item>
        <el-form-item class="row" label="案件描述">
          <el-input type="textarea" placeholder="请描述案件" v-model="description"></el-input>
        </el-form-item>

        <el-form-item class="row" label="图片信息">

          <el-upload v-model="fileList" action="/upload" :headers="header" :on-success="upOk" :on-error="upFail"
            list-type="picture-card" :auto-upload="true">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" fit="fill">
              <span class="el-upload-list__item-actions">
                <!-- <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span> -->
              </span>
            </div>
          </el-upload>


          <!-- <el-upload class="upload-demo" action="/upload" :on-success="upOk" :on-error="upFail" 
          :headers="{'token':'71E737C52A934D798C29C747D6D59C00'}"
             :file-list="fileList" list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>-->

        </el-form-item>


        <el-form-item style="text-align: right;">
          <el-button type="primary" @click="visible = false">取消</el-button>
          <el-button type="danger" @click="save">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 派遣弹窗 -->
    <el-dialog :visible.sync="dispatch">
      <taskDetail @back="backtap" ref="taskDetail"></taskDetail>
      <!-- <el-form ref="editForm" :model="editForm">
        <el-form-item label="派遣对象">
          <el-select v-model="patchUser" filterable placeholder="请选择">
            <el-option v-for="item in dispatchUser" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="派遣意见">
          <el-input type="textarea" placeholder="请输入派遣意见" v-model="dispatchSuggest">

        </el-form-item>
        <el-form-item style="text-align: right;">
          <el-button type="primary" @click="dispatch = false">取消</el-button>
          <el-button type="danger" @click="saveDispatch">确定</el-button>
        </el-form-item>
      </el-form> -->
    </el-dialog>
    <!-- 详情弹窗 -->
    <el-dialog :visible.sync="showDetail">
      <el-row :gutter="20">
        <div class="grid-content  marleft we700">申请单位：{{company}}</div>
        <div class="grid-content  marleft we700 martop20">申请人：{{poUser}}</div>
        <div class="grid-content  marleft we700 martop20">{{firstTypeDetail}}-{{secondTypeDetail}}</div>
        <div class="grid-content  marleft we700 martop20">申请时间：{{createTimeString}}</div>
        <div class="grid-content  marleft we700 martop20">问题描述：{{ddesc}}</div>
        <div v-if="imgList!=''" class="grid-content  marleft we700 martop20">
          图片信息：
          <div class="martop20" v-for="imgUrl in imgList">
            <!-- <img :src="imgUrl"> -->
            <el-image :src="imgUrl" fit="fill"></el-image>
          </div>
        </div>
      </el-row>
      <el-button type="primary" @click="showDetail = false">确定</el-button>
    </el-dialog>
    <!-- 案件流程 -->
    <el-dialog :visible.sync="showCaseLog">
      <el-form ref="editForm" :model="editForm">
        <el-form-item label="申请单位"></el-form-item>
        <el-form-item label="申请人"></el-form-item>
        <el-form-item label="大类-小类"></el-form-item>
        <el-form-item label="申请时间"></el-form-item>
        <el-form-item label="问题描述"></el-form-item>
        <el-form-item label="图片"></el-form-item>

        <el-form-item style="text-align: right;">
          <el-button type="primary" @click="showCaseLog = false">确定</el-button>
          <!-- <el-button type="danger" @click="saveDispatch">确定</el-button> -->
        </el-form-item>
      </el-form>
    </el-dialog>
  </master>
</template>
<script type="text/javascript">
  (function (G) {
    G.vue({
      "usingComponents": {//引入组件
        "master": "/components/Master/Master",//母版组件
        "taskDetail": "/pages/flow/task/detail",
        "mixinput": "/components/Input/Mixinput/Mixinput"
      },
      "enablePullDownRefresh": true
    }, {
      data: {
        value1: [new Date(2022, 0, 1, 0, 0), new Date()],
        location: null,// 
        location1: null,// 
        imgList: [],//图片组
        ddesc: '',//问题描述
        createTimeString: '',//申请时间
        firstTypeDetail: '',//大类
        secondTypeDetail: '',//小类
        poUser: '',//申请人
        company: '',//申请单位
        showCaseLog: false,//是否显示流程
        showDetail: false,//是否显示详情框
        selectCase: '',//选择的案件id
        dispatchSuggest: '',// 派遣意见
        patchUser: '', //指派用户
        dispatchUser: [],//可以指派的所有用户
        urgency: '',//紧急程度
        urgencyValue: [//紧急程度下拉
          { label: '普通', value: '1' },
          { label: '紧急', value: '2' }
        ],
        applyType: '',//申请类型
        applyTypeValue: [//申请类型下拉
          { label: '新案件', value: '1' },
          { label: '延期案件', value: '2' },
          { label: '挂账案件', value: '3' },
          { label: '回退案件', value: '4' },
          { label: '简易案件', value: '5' },
          { label: '已处理', value: '6' }
        ],
        header: {},//头文件
        params: {//页面请求参数
          pageSize: 10,
          pageNum: 1,
          applyType: 2,
          status: { $ne: 4 }
        },
        total: 0,//总数据量
        rows: [],//列表数据
        visible: false, // 新增和编辑弹窗
        dispatch: false, // 派遣弹窗
        editForm: {},//新增或者编辑的时候传入弹窗的值
        description: '',//案件描述
        type: '',//类型
        typeValue: [
          { label: '事件', value: '1' },
          { label: '部件', value: '2' }
        ],
        firstType: '',//大类
        firstTypeValue: [
          { label: '市容环境设施', value: '1' },
          { label: '交通设施', value: '2' },
          { label: '公共设施', value: '3' },
          { label: '市容环境类', value: '4' },
          { label: '宣传广告', value: '5' },
          { label: '施工管理', value: '6' },
          { label: '突发事件', value: '7' },
          { label: '街面秩序', value: '8' }
        ],
        secondType: '',//小类
        sourceValue: [{
          label: '12319', value: '1'
        }, {
          label: '城管通', value: '2'
        }, {
          label: '其他', value: '3'
        }],
        source: '',//案件来源
        // upPortTime: '',// 上报时间
        surplusTime: '',//剩余时间
        file: '',//上传的图片
        applicant: '',//申请人
        applicantValue: [],
        fileList: [],//上传的图片组
      },
      // ******************method**********************
      methods: {
        caseLogButton(params) {
          console.log('--caseLogButton', params);
          this.showCaseLog = true
        },
        detailButton(params) {//详情页面
          console.log('--detailButton', params.img);
          // params.applicant //申请人id
          this.firstTypeDetail = params.firstType //大类
          if (params.firstType == 1) {
            this.firstTypeDetail = '设施'
          }
          if (params.firstType == 2) {
            this.firstTypeDetail = '资源'
          }

          this.secondTypeDetail = params.secondType //小类
          this.createTimeString = params.createTimeString //申请时间
          this.ddesc = params.description //问题描述
          this.imgList = params.img.split(',') //图片list

          G.get('/api/model/user', { 'id': params.applicant }).then(res => {
            if (!res.errorMsg) {
              // console.log('----res',res);
              this.poUser = res.name
              this.company = res.unitId
            }

          })

          this.showDetail = true
        },
        upOk(res) {// 上传图片成功
          this.fileList.push('/file/' + res.id);
          console.log('ok', this.fileList);
        },
        upFail(res) {// 上传图片失败
          console.log('fail', res);
        },
        // handleRemove(file, fileList) {//删除图片
        //   console.log('-----1','/file/'+file.response.id, this.fileList);
        //   // this.file = this.file.;
        //   this.fileList = this.delArrayDetail('/file/'+file.response.id, this.fileList)
        //   this.setData({
        //     fileList :this.delArrayDetail('/file/'+file.response.id, this.fileList)
        //   })
        // },


        saveDispatch() {// 派遣框点保存
          console.log('---派遣框点保存saveDispatch');
          if (this.patchUser === '') {
            G.toask('请选择指派人')
          } else {
            G.put('/api/model/g_case', {
              'id': this.selectCase,
              'dispatchUser': this.patchUser,
              'dispatchSuggest': this.dispatchSuggest,
              'status': 2
            }).then(res => {
              if (!res.errorMsg) {
                G.post('/v1/wecom/send_msg', {
                  userIds: this.patchUser,
                  text: {
                    content: '您有新案件需要处理！'
                  }
                }).then(res1 => {
                  if (!res1.errorMsg) {
                    this.params.pageNum = 1
                    this.getList()
                    this.dispatch = false
                  }
                })
              }
              else {
                G.toask(res.errorMsg)
              }
            })
          }
        },
        edit(row) {
          if (row) {
            console.log('编辑数据：', row);
          }
          this.editForm = row ? row : {}
          this.visible = true
          G.get('/api/model/user').then(res => {
            if (!res.errorMsg) {
              for (let i = 0; i < res.length; i++) {
                this.applicantValue.push({
                  label: res[i]['name'], value: res[i]['id']
                })
              }
            }
          })
        },
        aggree(paramJson) {
          // 同意弹窗
          this.$confirm('该案件将移入待处理，确认操作吗？', '同意提醒', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$message({
              type: 'success',
              message: '已同意',
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        },
        reject(paramJson) {
          // 拒绝弹窗
          this.$confirm('该案件将被退回给处理人员，确认操作吗？', '拒绝提醒', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$message({
              type: 'success',
              message: '已确定拒绝',
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            });
          });
        },
        appoint(paramJson) {
          // 指派弹窗
          // this.dispatchUser = []
          // this.patchUser = ''
          this.dispatch = true
          // console.log('----指派弹窗paramJson', paramJson);
          // this.selectCase = paramJson.id
          this.$nextTick(() => {
            this.$refs.taskDetail.init(paramJson.taskID)
          })
          // G.get('/api/model/user').then(res => {
          //   if (!res.errorMsg) {
          //     for (let i = 0; i < res.length; i++) {
          //       this.dispatchUser.push({
          //         'label': res[i]['name'], 'value': res[i]['id']
          //       })
          //     }
          //   }
          // })
        },
        // 编辑和新增的保存事件
        save() {
          this.$refs.editForm.validate((valid) => {
            if (valid) {
              this.editForm = {
                'applyType': this.applyType,
                'urgency': this.urgency,
                'source': this.source,
                'applicant': this.applicant,
                // 'upPortTime': this.upPortTime,
                'surplusTime': this.surplusTime,
                'type': this.type,
                'firstType': this.firstType,
                'secondType': this.secondType,
                'description': this.description,
                'img': this.fileList
              }
              if (this.editForm.id) {
                G.put('/api/model/g_case', this.editForm).then(res => {
                  if (!res.errorMsg) {
                    this.visible = false
                    G.toask('编辑新闻成功')
                    this.params.pageNum = 1
                    this.getList()
                  }
                })
              } else {
                console.log('--this.editForm', this.editForm);
                G.post('/api/model/g_case', this.editForm).then(res => {
                  if (!res.errorMsg) {
                    this.visible = false
                    G.toask('添加新闻成功')
                    this.params.pageNum = 1
                    this.getList()
                  }
                })
              }
            }
          })
        },
        sizeChange(pageSize) {
          this.params.pageSize = pageSize;
          this.params.pageNum = 1;
          this.getList();
        },
        currentChange(pageNum) {
          this.params.pageNum = pageNum;
          this.getList();
        },
        searchList() {
          console.log('---', this.value1);
          this.params.createTime = {$gte: this.value1[0].getTime(), $lte: this.value1[1].getTime()}
          if (this.location1) {
            this.params.location = { $regex: '.*?' + this.location1 + '.*?' }
          } else {
            this.params.location = { $regex: '.*?' }
          }
          this.params.pageNum = 1;
          this.getList();
        },
        getList() {
          this.header = {
            'token': G.Storage.get('userInfo').token
          };
          console.log('----this.params', this.params);
          G.get('/api/model/g_case', this.params).then((res) => {
            console.log('----res', res);
            if (res.rows) {
              this.total = parseInt(res.total);
              this.rows = res.rows;
              // 处理剩余时间显示
              let time1 = new Date().getTime();
              this.rows.forEach(element => {   // now-createTime
                // element.surplusTime 
                let hours = element.surplusTime - (time1 - element.createTime) / (60 * 60 * 1000) // 总小时数

                if (hours > 0) {
                  let day = Math.floor(hours / 24)
                  let hour = parseInt(hours - day * 24) //小时
                  let minutes = (hours - day * 24 - hour) * 60 //剩余总分钟
                  let minute = parseInt(minutes) //分钟
                  let second = parseInt((minutes - minute) * 60) //秒
                  element.surplusTime = day.toString() + '天' + hour.toString() + '小时' + minute.toString() + '分' + second.toString() + '秒'
                } else {
                  element.surplusTime = '已超时'
                }
              });
            }
            else {
              this.rows = []
              this.rows.push(res)
              this.params.pageNum = 1
              this.total = this.rows.length
            }
          });
        },
        // 流程失败提示报错，成功就隐藏
        backtap(e) {
          if(e) {
            if (e.errorMsg) {
              G.toask('处理失败：', e.errorMsg)
              this.getList()
            }
            else {
              this.dispatch = false
              // G.toask('处理成功')
              this.getList()
            }
          }
        },
        delArrayDetail(str, list) {
          let num = 0
          let list1 = []
          for (let i = 0; i < list.length; i++) {
            console.log('---', list[i]);
            if (list[i] != str) {
              list1.push(list[i])
            }
          }
          console.log(list1);
          return list1
        },
        getDefaultTime() {
          let d1 = new Date()
          let d2 = d1.setMonth(d1.getMonth() - 1)
          console.log('--d1 d2', d1, d2);
          this.value1 = [new Date(d2), new Date()]
        },


      },
      // 初始化调用
      mounted() {
        this.params = {//页面请求参数
          pageSize: 10,
          pageNum: 1,
          status: { $ne: 4 },
          applyType: 2
        },
          this.getList();
        this.getDefaultTime()
      }
    });
  })(Y)
</script>
<style scoped>
  .text1row {
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 100%;
    white-space: nowrap;
  }

  .text3row {
    overflow: hidden;
    text-overflow: ellipsis;
    width: 100%;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
    word-break: break-all;
  }
  .searchFormInputs {
    margin-top: 5px;
  }

  .searchForm {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }

  .row {
    display: flex;
    flex-direction: row;
  }

  .martop20 {
    margin-top: 5px;
  }

  .marleft {
    margin-left: 20px;
  }

  .el-row {
    margin-bottom: 20px;

    /* &:last-child {
      margin-bottom: 0;
    } */
  }

  .el-col {
    border-radius: 4px;
  }

  .bg-purple-dark {
    background: #99a9bf;
  }

  .bg-purple {
    background: #d3dce6;
    /*height: 200px;*/
  }

  .bg-purple-light {
    background: #e5e9f2;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }

  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }

  .center {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .we700 {
    font-weight: 400;
    color: black;
  }

  .wrap {
    display: flex;
    flex-wrap: wrap;
  }

  .border1 {
    border: solid 1px;
  }

  .maright {
    margin-right: 20px;
  }
</style>